import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog,
} from 'antd-mobile'
import classNames from 'classnames'

import styles from './index.module.scss'
import EditInput from './EditInput'
import EditList from './EditList'
import { useHistory } from 'react-router-dom'
import {
  getUserProfile,
  updatePhoto,
  updateUserProfile,
} from '@/store/actions/profile'
import { logout } from '@/store/actions/login'
import { useInitialState } from '@/utils/hooks'
import React, { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import moment from 'moment'

const Item = List.Item

const ProfileEdit = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const { profile } = useInitialState(getUserProfile, 'profile')
  type InputState = {
    type: '' | 'name' | 'intro'
    visible: boolean
  }

  type ListState = {
    type: '' | 'gender' | 'photo'
    visible: boolean
  }
  const [showInput, setShowInput] = useState<InputState>({
    type: '',
    visible: false,
  })

  const [showList, setShowList] = useState<ListState>({
    type: '',
    visible: false,
  })
  const [showDate, setShowDate] = useState<boolean>(false)
  const hideInput = () => {
    setShowInput({
      type: '',
      visible: false,
    })
  }
  const hideList = () => {
    setShowList({
      type: '',
      visible: false,
    })
  }
  const fileRef = useRef<HTMLInputElement>(null)
  const onChangePhoto = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const fd = new FormData()
      fd.append('photo', e.target.files[0])
      dispatch(updatePhoto(fd))
      Toast.show({
        content: '修改成功',
        icon: 'success',
      })
      hideList()
    }
  }

  const onUpdate = async (key: string, value: string) => {
    if (key === 'photo') {
      fileRef.current!.click()
      return
    }
    await dispatch(
      updateUserProfile({
        [key]: value,
      })
    )
    Toast.show({
      content: '修改成功',
      icon: 'success',
    })
    hideInput()
    hideList()
  }

  const onLogout = () => {
    Dialog.show({
      content: '你确定要退出吗?',
      closeOnAction: true,
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
          },
          {
            key: 'sure',
            text: '确定',
            bold: true,
            danger: true,
            onClick: () => {
              dispatch(logout())
              Toast.show({
                content: '退出成功',
              })
              history.push('/login')
            },
          },
        ],
      ],
    })
  }
  return (
    <div className={styles.root}>
      <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
          onBack={() => history.go(-1)}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={profile.photo} alt="" />
                </span>
              }
              arrow
              onClick={() => setShowList({ type: 'photo', visible: true })}
            >
              头像
            </Item>
            <Item
              arrow
              extra={profile.name}
              onClick={() => setShowInput({ type: 'name', visible: true })}
            >
              昵称
            </Item>
            <Item
              arrow
              extra={
                <span className={classNames('intro', 'normal')}>
                  {profile.intro}
                </span>
              }
              onClick={() => setShowInput({ type: 'intro', visible: true })}
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => setShowList({ type: 'gender', visible: true })}
            >
              性别
            </Item>
            <Item
              arrow
              extra={profile.birthday}
              onClick={() => setShowDate(true)}
            >
              生日
            </Item>
          </List>

          <DatePicker
            onCancel={() => setShowDate(false)}
            visible={showDate}
            title="选择生日"
            value={new Date(profile.birthday)}
            min={new Date('1900-01-01')}
            max={new Date()}
            onConfirm={async (value) => {
              await onUpdate('birthday', moment(value).format('YYYY-MM-DD'))
              setShowDate(false)
            }}
          ></DatePicker>
        </div>

        <div className="logout">
          <Button className="btn" onClick={onLogout}>
            退出登录
          </Button>
        </div>
      </div>
      <Popup
        visible={showInput.visible}
        position="right"
        bodyStyle={{ width: '100vw' }}
        destroyOnClose
      >
        <EditInput
          hideInput={hideInput}
          type={showInput.type}
          onUpdate={onUpdate}
        ></EditInput>
      </Popup>
      <Popup visible={showList.visible} position="bottom" destroyOnClose>
        <EditList
          hideList={hideList}
          type={showList.type}
          onUpdate={onUpdate}
        ></EditList>
      </Popup>

      <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
    </div>
  )
}

export default ProfileEdit
